<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use App\Admin\Models\storeGoodsIn;
use App\Admin\Models\Common;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;
use Encore\Admin\Facades\Admin;
use Illuminate\Support\Facades\Input;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use Field\Interaction\FieldTriggerTrait;
use Field\Interaction\FieldSubscriberTrait;

class StoreGoodsInController extends Controller
{
	use HasResourceActions, FieldTriggerTrait, FieldSubscriberTrait;

    /**
     * Index interface.
     *
     * @param Content $content
     * @return Content
     */
    public function index(Content $content)
    {
        return $content
            ->header('入库单')
            ->description('列表')
            ->body($this->grid());
    }

    /**
     * Create interface.
     *
     * @param Content $content
     * @return Content
     */
    public function create(Content $content)
    {
        return $content
            ->header('商品入库')
            ->description('新增')
            ->body($this->form());
    }

    /**
     * Edit interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function edit($id, Content $content)
    {
        return $content
            ->header('入库数量修改')
            ->description('编辑')
            ->body($this->formEdit()->edit($id));
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new StoreGoodsIn);
        $grid->sgiId('ID');
        $grid->sgiBatchCode('批次号');
        $grid->sgName('商品名称');
        $grid->sgiBatchPrice('批次总价');
        $grid->sgiNum('批次数量');
        $grid->sgiUnitPrice('批次单价');
        $grid->sgiCurrentAmount('未进货时库存数');
        $grid->sgiSurplus('批次剩余');
//      $grid->sgiMerchantName('货源商家');
//      $grid->sgiMerchantCharge('负责人姓名');
//      $grid->sgiMerchantMobile('联系电话');
        $grid->createTime('记录时间');
		$grid->filter(function($filter){

		    // 去掉默认的id过滤器
		    $filter->disableIdFilter();

		});

		$grid->actions(function ($actions) {
		    $actions->disableDelete();
//		    $actions->disableEdit();
		    $actions->disableView();
		});

		$grid->filter(function($filter){

		    // 去掉默认的id过滤器
		    // $filter->disableIdFilter();

		    $filter->column(1/2, function ($filter) {
                $filter->like('sgName', '商品名称');
			});
            
		    $filter->column(1/2, function ($filter) {
		    	$filter->like('sgiBatchCode', '批次号');
			});

		});

		// 默认展开筛选框
		$grid->expandFilter();

		// 禁用行选择checkbox
		$grid->disableRowSelector();

		// 禁用导出
		$grid->disableExport();
        return $grid;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Admin::Form(StoreGoodsIn::class, function (Form $form) {
			$form->hidden('sgiId');
			$todayBatchCode = date('Ymd', time());
			$form->text('sgiBatchCode', '批次号')->placeholder('不填默认为当天日期')->default($todayBatchCode)->help("默认为当天日期，可根据需要任意修改");
			$StoreGoodsIn = new StoreGoodsIn();
			$productData = $StoreGoodsIn->getStoreGoodsList();
			$form->select('sgId', '商品名')->options($productData);
			$form->text('sgiUnitPrice', '商品单价');
			$form->text('sgiNum', '进货数量')->default(1);
			$form->text('sgiBatchPrice', '批次总价');

        	// 弄一个触发事件的Script对象。
        	$trigger_script = $this->createTriggerScript($form);
        	// 添加事件响应事件
        	$subscriber_script = $this->createSubscriberScript($form, function($builder) {

				// 监听sgId的select事件
	            $builder->subscribe('sgId', 'select', function ($event) {
	                $script = <<<EOT
	                	function (data){
	                		var sgId = data.id;
							$.get("../../main/getStorePrice?sgId="+sgId, function(result){
								if (typeof(result) == "string"){
									result = JSON.parse(result);
								}
							    $("#sgiUnitPrice").val(result.data);

							    var sgiUnitPrice = $("#sgiUnitPrice").val();
							    var sgiNum = $("#sgiNum").val();
							    sgiNum = parseInt(sgiNum);
							    if (typeof(sgiNum) != 'number'){
							    	sgiNum = 1
							    }
							    $('#sgiBatchPrice').val(sgiUnitPrice*sgiNum);
							});
	                	}
EOT;
					return $script;
	            });

	            // 监听sgiUnitPrice的input事件
	            $builder->subscribe('sgiUnitPrice', 'input', function ($event) {
	                $script = <<<EOT
	                	function (data){
	                		var sgiUnitPrice = $("#sgiUnitPrice").val();
						    var sgiNum = $("#sgiNum").val();
						    sgiNum = parseInt(sgiNum);
						    if (typeof(sgiNum) != 'number'){
						    	sgiNum = 1
						    }
						    $('#sgiBatchPrice').val(sgiUnitPrice*sgiNum);
	                	}
EOT;
					return $script;
	            });

	            // 监听sgiNum的input事件
	            $builder->subscribe('sgiNum', 'input', function ($event) {
	                $script = <<<EOT
	                	function (data){
	                		var sgiUnitPrice = $("#sgiUnitPrice").val();
						    var sgiNum = $("#sgiNum").val();
						    sgiNum = parseInt(sgiNum);
						    if (typeof(sgiNum) != 'number'){
						    	sgiNum = 1
						    }
						    $('#sgiBatchPrice').val(sgiUnitPrice*sgiNum);
	                	}
EOT;
					return $script;
	            });

	            // 监听sgiUnitPrice的input事件
	            $builder->subscribe('sgiBatchPrice', 'input', function ($event) {
	                $script = <<<EOT
	                	function (data){
	                		var sgiBatchPrice = $("#sgiBatchPrice").val();
						    var sgiNum = $("#sgiNum").val();
						    sgiNum = parseInt(sgiNum);
						    if (typeof(sgiNum) != 'number'){
						    	sgiNum = 1
						    }
						    var sgiUnitPrice = sgiBatchPrice/sgiNum;
						    $('#sgiUnitPrice').val(sgiUnitPrice.toFixed(2));
	                	}
EOT;
					return $script;
	            });
       		});

       		/* 将 trigger_script 和 subscriber_script 注入 form 中 */
        	$form->scriptinjecter('name_no_care', $trigger_script, $subscriber_script);

            $form->tools(function (Form\Tools $tools) {

			    // 去掉`列表`按钮
//			    $tools->disableList();

			    // 去掉`删除`按钮
			    $tools->disableDelete();

			    // 去掉`查看`按钮
//			    $tools->disableView();

			    // 添加一个按钮, 参数可以是字符串, 或者实现了Renderable或Htmlable接口的对象实例
//			    $tools->add('<a class="btn btn-sm btn-danger"><i class="fa fa-trash"></i>&nbsp;&nbsp;delete</a>');
			});

			$form->footer(function ($footer) {

//			    // 去掉`重置`按钮
//			    $footer->disableReset();
//
//			    // 去掉`提交`按钮
//			    $footer->disableSubmit();

			    // 去掉`查看`checkbox
			    $footer->disableViewCheck();

			    // 去掉`继续编辑`checkbox
			    $footer->disableEditingCheck();

			    // 去掉`继续创建`checkbox
//			    $footer->disableCreatingCheck();

			});
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function formEdit()
    {
        return Admin::Form(StoreGoodsIn::class, function (Form $form) {

			$form->hidden('sgiId');
			$todayBatchCode = date('Ymd', time());
			$form->text('sgiBatchCode', '批次号')->readOnly();
			$StoreGoodsIn = new StoreGoodsIn();
			$productData = $StoreGoodsIn->getStoreGoodsList();
			$form->select('sgId', '商品名')->options($productData)->readOnly();
			$form->number('sgiChangeNum', '修改进货数量')->default("0")->help('正数增加，负数减少');
			$form->text('sgiSurplus', '批次剩余')->readOnly();

			$form->saving(function (Form $form) {

			    if ($form->sgiChangeNum + $form->sgiSurplus < 0){
			    	$error = new MessageBag([
//				        'title'   => $sId.'|'.$muId.'|'.$sgId,
						'title'   => '提交失败',
				        'message' => '减少数量不能小于批次剩余数量'
				    ]);

				    return back()->with(compact('error'))->withInput();
			    }
			});

        	// 弄一个触发事件的Script对象。
        	$trigger_script = $this->createTriggerScript($form);
        	// 添加事件响应事件
        	$subscriber_script = $this->createSubscriberScript($form, function($builder) {

				// 监听sgId的select事件
	            $builder->subscribe('sgId', 'select', function ($event) {
	                $script = <<<EOT
	                	function (data){
	                		var sgId = data.id;
							$.get("../../main/getStorePrice?sgId="+sgId, function(result){
								if (typeof(result) == "string"){
									result = JSON.parse(result);
								}
							    $("#sgiUnitPrice").val(result.data);

							    var sgiUnitPrice = $("#sgiUnitPrice").val();
							    var sgiNum = $("#sgiNum").val();
							    sgiNum = parseInt(sgiNum);
							    if (typeof(sgiNum) != 'number'){
							    	sgiNum = 1
							    }
							    $('#sgiBatchPrice').val(sgiUnitPrice*sgiNum);
							});
	                	}
EOT;
					return $script;
	            });

	            // 监听sgiUnitPrice的input事件
	            $builder->subscribe('sgiUnitPrice', 'input', function ($event) {
	                $script = <<<EOT
	                	function (data){
	                		var sgiUnitPrice = $("#sgiUnitPrice").val();
						    var sgiNum = $("#sgiNum").val();
						    sgiNum = parseInt(sgiNum);
						    if (typeof(sgiNum) != 'number'){
						    	sgiNum = 1
						    }
						    $('#sgiBatchPrice').val(sgiUnitPrice*sgiNum);
	                	}
EOT;
					return $script;
	            });

	            // 监听sgiNum的input事件
	            $builder->subscribe('sgiNum', 'input', function ($event) {
	                $script = <<<EOT
	                	function (data){
	                		var sgiUnitPrice = $("#sgiUnitPrice").val();
						    var sgiNum = $("#sgiNum").val();
						    sgiNum = parseInt(sgiNum);
						    if (typeof(sgiNum) != 'number'){
						    	sgiNum = 1
						    }
						    $('#sgiBatchPrice').val(sgiUnitPrice*sgiNum);
	                	}
EOT;
					return $script;
	            });

	            // 监听sgiUnitPrice的input事件
	            $builder->subscribe('sgiBatchPrice', 'input', function ($event) {
	                $script = <<<EOT
	                	function (data){
	                		var sgiBatchPrice = $("#sgiBatchPrice").val();
						    var sgiNum = $("#sgiNum").val();
						    sgiNum = parseInt(sgiNum);
						    if (typeof(sgiNum) != 'number'){
						    	sgiNum = 1
						    }
						    var sgiUnitPrice = sgiBatchPrice/sgiNum;
						    $('#sgiUnitPrice').val(sgiUnitPrice.toFixed(2));
	                	}
EOT;
					return $script;
	            });
       		});

       		/* 将 trigger_script 和 subscriber_script 注入 form 中 */
        	$form->scriptinjecter('name_no_care', $trigger_script, $subscriber_script);

            $form->tools(function (Form\Tools $tools) {

			    // 去掉`列表`按钮
//			    $tools->disableList();

			    // 去掉`删除`按钮
			    $tools->disableDelete();

			    // 去掉`查看`按钮
//			    $tools->disableView();

			    // 添加一个按钮, 参数可以是字符串, 或者实现了Renderable或Htmlable接口的对象实例
//			    $tools->add('<a class="btn btn-sm btn-danger"><i class="fa fa-trash"></i>&nbsp;&nbsp;delete</a>');
			});

			$form->footer(function ($footer) {

//			    // 去掉`重置`按钮
//			    $footer->disableReset();
//
//			    // 去掉`提交`按钮
//			    $footer->disableSubmit();

			    // 去掉`查看`checkbox
			    $footer->disableViewCheck();

			    // 去掉`继续编辑`checkbox
			    $footer->disableEditingCheck();

			    // 去掉`继续创建`checkbox
//			    $footer->disableCreatingCheck();

			});
        });
    }

}
